package com.heima.user.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.utils.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;


@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

@Autowired
private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        //先判断传入的值dto是否为空
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        String password = dto.getPassword();
        String phone = dto.getPhone();
        //先判断输入的手机号和密码是否存在
        if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(password)){
            //如果判断为空则说明是游客登陆

            //直接生成token
            String token = AppJwtUtil.getToken(0L);

            //用集合把user和token封装起来,并返回结果
            Map<String, Object> map = new HashMap<>(2);
            map.put("user" ,null);
            map.put("token" ,token);

            return ResponseResult.okResult(map);
        }

        //正常登录
        //判断数据库手机号是否存在

        //条件构造器
        LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApUser::getPhone,phone);  //根据手机号在数据库中查询
        ApUser apUser = apUserMapper.selectOne(queryWrapper);

        if (apUser ==null){  //像前端返回手机号不存在
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //密码比对
        String salt = apUser.getSalt();
        String passwordDb = apUser.getPassword();  //数据库中的密码
//.getBytes是因为只能接收字节码
        String md5DigestAsHex = DigestUtils.md5DigestAsHex((password+salt).getBytes());
        if (!md5DigestAsHex.equals(passwordDb)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);

        }
//清空敏感数据
        apUser.setSalt("");
        apUser.setPassword("");

        //直接生成token
        String token = AppJwtUtil.getToken(apUser.getId().longValue());

        //用集合把user和token封装起来,并返回结果
        Map<String, Object> map = new HashMap<>(2);
        map.put("user" ,apUser);
        map.put("token" ,token);
//返回结果
        return ResponseResult.okResult(map);


    }
}